<?php

namespace app\stores\controller\miniapp\coupon;

use app\BaseController;
use app\beautiful\logic\LogsLogic;
use app\beautiful\logic\PartnerLogic;
use app\beautiful\model\CouponModel;
use app\beautiful\model\logs\PartnerGiftbagLogsModel;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\PartnerGiftbagModel;
use app\beautiful\model\PartnerModel;
use app\common\logic\DataLogic;

class Coupon extends BaseController{

    /*获取可领取的优惠券(不用积分兑换)*/
    public function getCouponDatas(){

        $today = date('Y-m-d', $this->request->time());

        $where=[

            ['shop_id','=',$this->request->shopId],

            ['status','=',1],

            ['is_delete','=',0],

            ['quota','>',0],

            ['start_time','<=',$today],

            ['end_time','>=',$today],

            ['is_integral_exchange','=',0],

            ['type_id','in',[1,2]],

        ];

        $return = [];

        $return['hasIds'] = [];

        //如果memberId 不为空的情况下

        if($this->request->memberId){

            if(null === $member = MemberModel::find($this->request->memberId)){

                return $this->error('用户登录状态不正确',100);

            }
            $level = verifyMemberLevel($this->request->shopId,$this->request->memberId);
            if(empty($level)){

                return $this->error('用户登录状态不正确',100);

            }

            $where[]= $member->level === null ? ['type_id','=',1] : ['type_id','IN',[1,3]];



            $hasIds = MemberCouponModel::where([

                    ['member_id','=', $this->request->memberId],

                    ['shop_id','=', $this->request->shopId],

                    ['type_id','=',1]

                ])->column('coupon_id') ?? [];

            $return['hasIds'] = $hasIds;

        }else{ //非登录情况只显示普通券

            $where[]=['type_id','=',1];

        }



        $coupons = CouponModel::where($where)

            ->order(['update_time'=>'desc','add_time'=>'desc'])

            ->limit($this->request->limit)->page($this->request->page)

            ->field('coupon_id,name,valid_bg_time,valid_end_time,coupon_money,money_limit')

            ->select()->toArray();

        $return['coupons']=$coupons;

        return $this->success($return);

    }

    /*领取优惠券（缺少一键领取功能）(不用积分兑换)*/
    public function getCoupon(){

        $coupon_id = $this->request->param('coupon_id/d');
        $partner_id = $this->request->param('partner_id/d',0);
        $giftbag_id = $this->request->param('giftbag_id/d',0);



        if(empty($coupon_id)){

            return $this->error('请选择要领取的优惠券');

        }



        $today=date('Y-m-d',$this->request->time());

        $is_exist=MemberCouponModel::where([

            ['member_id','=', $this->request->memberId],

            ['shop_id','=', $this->request->shopId],

            ['coupon_id','=',$coupon_id],

            ['type_id','=',1]

        ])->find();

        if($is_exist){

            return $this->error('此优惠券您已领过');

        }



        if(null === $coupon = CouponModel::where('coupon_id',$coupon_id)->lock(true)->find()){

            return $this->error('优惠券不存在');

        }

        if($coupon->is_delete == 1 || $coupon->shop_id != $this->request->shopId ){

            return $this->error('优惠券不存在');

        }

        if($coupon->status == -1){

            return $this->error('优惠券已经下架');

        }

        if($coupon->quota <= 0){

            return $this->error('优惠券已经领完了');

        }

        if($coupon->start_time > $today || $coupon->end_time < $today){

            return $this->error('优惠券已经过期了');

        }

        if($coupon->is_integral_exchange==1){

            return $this->error('该优惠券只能积分兑换无法领取');

        }



        $member=$this->request->member;

        $type_id = $member->level === null ? 1 : 3;


        if($coupon->type_id > $type_id  &&  $coupon->type_id != 5 ){

            return $this->error('该券为会员券，普通用户无法领取');

        }



        $coupon->quota = $coupon->quota - 1;

        $coupon->take_count = $coupon->take_count + 1;

        $mCoupon = new  MemberCouponModel();



        $mCoupon->save([

            'shop_id'       => $this->request->shopId,

            'member_id'     => $this->request->memberId,

            'type_id'       => 1,

            'coupon_id'     => $coupon->coupon_id,

            'name'          => $coupon->name,

            'coupon_money'  => $coupon->coupon_money,

            'money_limit'   => $coupon->money_limit,

            'valid_bg_time' => $coupon->valid_bg_time,

            'valid_end_time'=> $coupon->valid_end_time,

            'status'        => 0

        ]);

        $coupon->save();


        $coupon_type_id = 8;


        //合伙人绑定

        if(!empty($partner_id)){
            if(null === $partner = PartnerModel::find($partner_id)) return $this->error('合伙人不存在');

            $PartnerLogic = new PartnerLogic($this->request->shopId);
            $is_new = true;
            $pmember = MemberModel::where([

                ['shop_id','=',$this->request->shopId],

                ['mobile','=',$partner->mobile]

            ])->find();

            if(null === $pmember) return $this->error('合伙人设置错误');

            $PartnerLogic->bindPartner($this->request->memberId, $pmember->member_id,$is_new);

            $coupon_type_id = 22;

            //领取礼包记录
            $this->partnerGiftbagLog($partner_id,$giftbag_id,$this->request->shopId,$this->request->memberId);

        }

        LogsLogic::coupon($this->request->shopId,$member->member_id,1,$coupon_type_id,$mCoupon->member_coupon_id,'',0);


        return $this->success([]);

    }

    /*优惠券*/
    public function couponList(){
        $now = date('y-m-d');
        $where = [
            ['shop_id','=',$this->request->shopId],
            ['status','=',1],
            ['is_delete','=',0],
            ['start_time','<=',$now],
            ['end_time','>=',$now],
            ['valid_end_time','>=',$now],
            ['quota','>',0],
            ['type_id','in',[1,2]],
        ];

        $coupon=new CouponModel();

        $order=['update_time'=>'desc','add_time'=>'desc'];

        $field="coupon_id,name,type_id,valid_bg_time,valid_end_time,coupon_money,money_limit,add_time";

        $append=['add_time_format'];

        $return = DataLogic::getDataList($coupon,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        return $this->success($return);
    }
    /**
     * 优惠券礼包领取记录
     * @param $partner_id
     * @param $giftbag_id
     * @param $shopId
     * @param $memberId
     */
    public function partnerGiftbagLog($partner_id,$giftbag_id,$shop_id,$member_id)
    {

        $partner_giftbag_log =PartnerGiftbagLogsModel::where([

            ['member_id','=', $member_id],

            ['shop_id','=', $shop_id],

            ['partner_id','=',$partner_id],

            ['giftbag_id','=',$giftbag_id],

        ])->find();

        if(! $partner_giftbag_log){

            $partner_giftbag_log = new PartnerGiftbagLogsModel();

            $partner_giftbag_log->shop_id=$shop_id;

            $partner_giftbag_log->member_id=$member_id;

            $partner_giftbag_log->partner_id=$partner_id;

            $partner_giftbag_log->giftbag_id=$giftbag_id;

            $partner_giftbag_log->save();

            //扣减合伙人礼包数量
            $partner_giftbag =PartnerGiftbagModel::where([

                ['shop_id','=', $shop_id],

                ['partner_id','=',$partner_id],

                ['giftbag_id','=',$giftbag_id],

            ])->find();

            if($partner_giftbag && $partner_giftbag->remand_qty > 0){
                $partner_giftbag->remand_qty = $partner_giftbag->remand_qty -1;
                $partner_giftbag->save();
            }

        }

        return true;

    }


}

